#!/usr/bin/env python

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from core.sm2 import SM2

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////davinci.db'
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = "users"
 
    id = db.Column(db.Integer, primary_key=True)
    email_address = db.Column(db.String, nullable=False)  
    fullname = db.Column(db.String)
    password = db.Column(db.String, nullable=False)
 
    def __init__(self, email_address, fullname, password):
        self.name = name
        self.email_address = email_address
        self.fullname = fullname
        self.password = password
        
class Node(db.Model):
    
    __tablename__ = "nodes"
 
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    description = db.Column(db.String)
    parent_id = db.Column(db.Integer, db.ForeignKey('nodes.id'))
    children = db.relationship('Node',
                            cascade = "all",
                            backref = db.backref("parent", remote_side='Node.id')
                            )
    cards = db.relationship('Card',
                            cascade = "all",
                            backref = db.backref("node", remote_side='Node.id')
                            )
     
    def __init__(self, name, parent = None, description = None):
        self.name = name
        self.description = description
        self.parent = parent
 

class Card(db.Model):
    
    __tablename__ = "cards"
    id = db.Column(db.Integer, primary_key=True)
    question = db.Column(db.String, nullable=False)
    hint = db.Column(db.String)
    answer = db.Column(db.String)
    node_id = db.Column(db.Integer, db.ForeignKey('nodes.id'))
 
    def __init__(self, question, hint = None, answer = None, node = None):
        self.question = question
        self.hint = hint
        self.answer = answer
        self.node = node
 
 
class Statistic(db.Model, SM2):
    
    __tablename__ = "statistics"
    
    id = db.Column(db.Integer, primary_key=True)
    easiness_factor = db.Column(db.Float, nullable=False)
    number_repetitions = db.Column(db.Integer, nullable=False)
    quality_of_last_recall = db.Column(db.Integer)
    repetition_interval = db.Column(db.Integer)
    next_repetition = db.Column(db.Date)
    last_studied = db.Column(db.Date)
    
    node_id = db.Column(db.Integer, db.ForeignKey('cards.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    
    def __init__(self):
        pass
    

def dump_tree(node, indent=0):

    return "&nbsp;&nbsp;" * indent + node.name + \
                "<br>" + \
                "".join([
                    dump_tree(c, indent +1) 
                    for c in node.children]) + \
                ",".join([
                    c.question
                    for c in node.cards])
